<script setup lang="ts">
import { Lock, User, Refresh } from '@element-plus/icons-vue'
import useAuth from '@renderer/composables/useAuth'
import useCodeLogin from '@renderer/composables/useCodeLogin'
import useStorage from '@renderer/composables/useStorage'
import { CacheEnum } from '@renderer/enum/CacheEnum'
import { ref } from 'vue'
import { CloseSmall } from '@icon-park/vue-next'
import { ElMessage } from 'element-plus'
import QRCode from 'qrcode'
type LoginType = 'passwordLogin' | 'codeLogin'
const loginType = ref<LoginType>('passwordLogin')
const qrCodeUnique = ref<{ status: string; unique: string; avatar?: string; token?: string }>({
  status: '',
  unique: '',
})
const qrStatusInterval = ref()
const handleLoginType = async (type: LoginType) => {
  loginType.value = type
  if (type == 'codeLogin') {
    await handleGetQrCode()
  } else {
    clearInterval(qrStatusInterval.value)
  }
}
const isRemember = ref(false)
const { form, login, loginInit } = useAuth()
const { getScanQrCode, checkQrScan } = useCodeLogin()
const store = useStorage()
const handleLogin = async () => {
  if (isRemember.value) {
    if (form.account && form.password) {
      await store.set('account', form.account)
      await store.set('password', form.password)
    } else {
      ElMessage.error('请输入账号密码')
      return
    }
  } else {
    await store.remove('account')
    await store.remove('password')
  }
  await login()
}
const closeWindow = () => {
  window.api.closeWindow('login', 'destroy')
}
const checkQrStatus = async () => {
  const res = await checkQrScan({ unique: qrCodeUnique.value.unique })
  qrCodeUnique.value = res
  if (res.status == 'cancel') {
    ElMessage.error('请重新扫码登录')
    await handleGetQrCode()
  } else if (res.status == 'confirm') {
    clearInterval(qrStatusInterval.value)
    await loginInit(res.token)
  }
}
const handleGetQrCode = async () => {
  await getScanQrCode()?.then((res) => {
    qrCodeUnique.value = res
    const canvas = document.getElementById('qrcode')
    QRCode.toCanvas(canvas, qrCodeUnique.value.unique, (error) => {
      if (error) {
        ElMessage.error('二维码生成失败')
      }
    })
  })
  qrStatusInterval.value = setInterval(async () => {
    await checkQrStatus()
  }, 500)
}
const initPage = async () => {
  store.remove(CacheEnum.TOKEN_NAME)
  clearInterval(qrStatusInterval.value)
  const account = await store.get('account')
  const password = await store.get('password')
  if (account && password) {
    form.account = account
    form.password = password
    isRemember.value = true
  }
}
await initPage()
</script>

<template>
  <main class="main">
    <CloseSmall
      theme="outline"
      size="30"
      class="cursor-pointer absolute top-2 right-2 nodrag"
      fill="#888888"
      @click="closeWindow" />
    <template v-if="loginType == 'passwordLogin'">
      <div class="loginLog">
        <img src="../../public/webLoginLogo.png" />
      </div>
      <div class="loginType nodrag">
        <span
          :class="loginType == 'passwordLogin' ? 'activeSpan' : 'defaultSpan'"
          @click="handleLoginType('passwordLogin')"
          >密码登录</span
        >
        <span class="defaultSpan" @click="handleLoginType('codeLogin')">扫码登录</span>
      </div>
      <div class="loginForm nodrag mt-6">
        <el-input v-model="form.account" placeholder="请输入您的账号" size="large">
          <template #prefix>
            <el-icon :size="20"><User /></el-icon>
          </template>
        </el-input>
        <el-input v-model="form.password" placeholder="请输入您的密码" size="large" type="password" show-password>
          <template #prefix>
            <el-icon :size="20"><Lock /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="flex items-center justify-end nodrag">
        <el-checkbox v-model="isRemember">记住密码</el-checkbox>
      </div>
      <div
        class="rounded-full py-3 text-center nodrag cursor-pointer mt-6"
        @click.stop="handleLogin"
        style="background: linear-gradient(-90deg, #ff9600, #ffb242)">
        <span class="font-bold text-base text-white">登录</span>
      </div>
    </template>
    <template v-if="loginType == 'codeLogin'">
      <div
        class="flex justify-center items-center flex-col mt-10"
        v-show="qrCodeUnique.status == 'expired' || qrCodeUnique.status == 'wait_scan'">
        <span class="text-xl text-[#FF9600] font-bold">扫码登录</span>
        <div class="w-[250px] h-[250px] relative">
          <canvas id="qrcode" style="height: 100%; width: 100%"></canvas>
          <div class="qr_mask nodrag" @click="handleGetQrCode" v-if="qrCodeUnique.status == 'expired'">
            <el-icon :size="50" color="#fff"><Refresh /></el-icon>
            <p>请点击刷新重新获取二维码</p>
          </div>
        </div>
        <span class="text-gray-500 text-base cursor-pointer nodrag" @click="handleLoginType('passwordLogin')">
          切换密码登录
        </span>
      </div>
      <div class="flex flex-col justify-between mt-10 items-center h-screen pb-10" v-if="qrCodeUnique.status == 'scan'">
        <div class="flex flex-col items-center gap-6">
          <img :src="qrCodeUnique.avatar" class="w-[80px] h-[80px] rounded-sm" />
          <span class="text-green-500 text-sm">扫码完成</span>
          <span class="text-gray-500 text-sm">需在手机上完成登录</span>
        </div>
        <span class="text-blue-500 text-base cursor-pointer nodrag">取消</span>
      </div>
    </template>
  </main>
</template>
<style lang="scss" scoped>
.main {
  @apply bg-white flex flex-col px-10 pt-4 h-screen rounded-lg shadow-slate-950;
  .loginLog {
    @apply flex justify-center items-center;
    img {
      width: 114px;
      height: 88px;
    }
  }
  .loginType {
    @apply flex justify-around py-4;
    span {
      @apply text-xl flex-1 text-center cursor-pointer font-bold;
    }
    span:nth-child(1) {
      border-right: 1px solid #6c7785;
    }
    .defaultSpan {
      @apply text-[#d4d4d4];
    }
    .activeSpan {
      @apply text-[#313131];
    }
  }
  .loginForm {
    @apply mb-2 mt-2 flex flex-col gap-8;
    .codeBtn {
      @apply w-[150px] flex justify-center items-center rounded-2xl;
    }
  }
  #qrcode {
    width: 250px !important;
    height: 250px !important;
  }
  .qr_mask {
    @apply absolute w-[200px] h-[200px] flex justify-center items-center flex-col gap-5 cursor-pointer top-[25px] left-[25px];
    background: rgba(0, 0, 0, 0.5);
    p {
      @apply text-white text-center text-sm;
    }
  }
}
::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #ff9600 !important;
}
::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background: #ff9600 !important;
  border-color: #ff9600 !important;
}
</style>
